package com.huidu.bitrade.interceptor;


import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.huidu.bitrade.constant.CommonStatus;
import com.huidu.bitrade.constant.SysConstant;
import com.huidu.bitrade.entity.Member;
import com.huidu.bitrade.entity.transform.AuthMember;
import com.huidu.bitrade.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.swagger.web.ApiResourceController;
import springfox.documentation.swagger2.web.Swagger2ControllerWebMvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author QQ：97095646
 * @date 2020年01月11日
 */
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {
    public String authorization; // 用于测试环境进行管理员操作
    private boolean swaggerEnable;

    public MemberInterceptor (boolean swaggerEnable){
        this.swaggerEnable = swaggerEnable;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if(((HandlerMethod) handler).getBean() instanceof ApiResourceController ||
                ((HandlerMethod) handler).getBean() instanceof Swagger2ControllerWebMvc
        ){
            return swaggerEnable ? true : false;
        }
        if(authorization != null && authorization.equalsIgnoreCase(request.getHeader("authorization"))) return true;
        HttpSession session = request.getSession();
        log.info(request.getRequestURL().toString());
        AuthMember user = (AuthMember) session.getAttribute(SysConstant.SESSION_MEMBER);
        if (user != null) {
            //user.getStatus()状态可能不实时，所以要去数据库查
            //解决service为null无法注入问题
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            MemberService memberService = (MemberService) factory.getBean("memberService");
            Member member = memberService.findOne(user.getId());
            if(member.getStatus().getOrdinal()==(CommonStatus.NORMAL.getOrdinal())){
                return true;
            }
            //如果用户是禁用状态，踢用户下线
            session.removeAttribute(SysConstant.SESSION_MEMBER);
            ajaxReturn(response, 4000, "The current login status has expired, please login again!");
        }else {
            ajaxReturn(response, 4000, "The current login status has expired, please login again!");
        }
        return false;
    }


    public static void ajaxReturn(HttpServletResponse response, int code, String msg) throws IOException, JSONException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json; charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("message", msg);
        out.print(json.toString());
        out.flush();
        out.close();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}
